//
//  LPBaseNetWorking.swift
//  TLenPoint
//
//  Created by Docker on 2018/3/21.
//  Copyright © 2018年 Docker. All rights reserved.
//

import UIKit
import YYModel
import AdSupport
class LPBaseNetWorking: NSObject {

    /// 获取token值的方法
    ///
    /// - Parameters:
    ///   - requestType: 请求类型
    ///   - urlString: url地址
    ///   - params: 参数
    ///   - callBack: 回调值
   private func Hp_requestTokeAction(requestType:RequestType, urlString:String,params:Any?,callBacks:@escaping (Any?)->()){
        let adId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        let dict = ["mobileType":"iOS","mobileId":adId]
        //打印响应体
        CommanAction().LPLogLine(message: urlString)
       let urlStrings = urlString + "/get-access-token"
        LPNetWroking.lpsessionManager.requestData(requestType: requestType, urlString: urlStrings, params: dict) { (response, error) in
            callBacks(response)
           
        }
    }
    
    /// 请求通用方法
    ///
    /// - Parameters:
    ///   - requestType: 请求类型
    ///   - urlString: 请求地址
    ///   - params: 请求参数
    ///   - actionName: 请求的地址名称
    ///   - callBack: 会调值
    func Hp_WithRequestType(requestType:RequestType,urlString:String,params:Any?,actionName:String,callBack:@escaping (Any?,Error?)->()){
        //先判断本地是否又Token
        let userModel = LPTokenModel.loadUserAccount()
        if((userModel?.access_token) != nil){
            self.Hp_equestAction(requestType: requestType, urlString: urlString, params: params, actionName: actionName, callBack: { (response,error) in
                let dic = response as! [String: Any]
                let result = dic["resultCode"] as! NSInteger
                if (result == -1){
                    //token失效重新获取
                    self.Hp_requestTokeAction(requestType: requestType, urlString: urlString, params: params, callBacks: { (responase) in
                        //打印响应体
                        let dic = responase as! [String: Any]
                        userModel?.access_token = (dic["accessToken"] as! String)
                        userModel?.secretKey = (dic["secretKey"] as! String)
                        userModel?.saveUserAccount()
                        CommanAction().LPLogLine(message: responase)
                        self.Hp_equestAction(requestType: requestType, urlString: urlString, params: params, actionName: actionName, callBack: { (responses,error) in
                            let dic = responses as! [String: Any]
                            let result = dic["resultCode"] as! NSInteger
                            if (result == 0){
                            callBack(responses, nil)
                            }else{
                                callBack(nil, error)
                            }
                        })
                    })
                }else{
                   callBack(response, nil)
                }
            })
        }else{
            //token没有失效
            self.Hp_requestTokeAction(requestType: requestType, urlString: urlString, params: params, callBacks: { (responase) in
               
                let dic = responase as! [String: Any]
                let newuserModel = LPTokenModel(dic: dic)
                newuserModel.access_token = (dic["accessToken"] as! String)
                newuserModel.secretKey = (dic["secretKey"] as! String)
                newuserModel.saveUserAccount()
                CommanAction().LPLogLine(message: responase)
                self.Hp_equestAction(requestType: requestType, urlString: urlString, params: params, actionName: actionName, callBack: { (responses,error) in
                    let dic = responses as! [String: Any]
                    let result = dic["resultCode"] as! NSInteger
                    if (result == 0){
                        callBack(responses, nil)
                    }else{
                        callBack(nil, error)
                    }
                })
            })
        }
    }
    
  ///     请求通用方法签名
  ///
  /// - Parameters:
  ///   - requestType: 请求类型
  ///   - urlString: 地址
  ///   - params: 参数
  ///   - actionName: 地址名
  ///   - callBack: 返回值
  private  func Hp_equestAction(requestType:RequestType,urlString:String,params:Any?,actionName:String,callBack:@escaping (Any?,Error?)->()){
        var body = [String: Any]()
        let userModel = LPTokenModel.loadUserAccount()
        body["accessToken"] = userModel?.access_token
        body["actionName"] = actionName
        let dict = params as! NSDictionary
        var payload = dict.yy_modelToJSONString()
        let date = NSDate()
        let timeInterval = date.timeIntervalSince1970 * 1000
        let time = Int(timeInterval)
        let strValue1 = String(time)
        if payload == nil{
            payload = "{}"
        }

        let access_token = userModel!.access_token as! String
        let secretKey = userModel!.secretKey as! String
        let pay = payload as! String
        body["timestamp"] = strValue1
        var sign = access_token + "\(actionName)" + pay + "\(strValue1)" + secretKey
   
        print(String(describing: userModel?.access_token))
        print(String(describing: userModel?.secretKey))
        sign = sign.lp_sha1()
        body["payload"] = payload
        body["sign"] = sign
        let apiUrlString = urlString + "/api"
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        let lenfrome = ["appType":"1","appVersion":currentVersion,"channelCode":"lepoint"] as NSDictionary
        let lenFromStr = lenfrome.yy_modelToJSONString()
        body["from"] = lenFromStr

        LPNetWroking.lpsessionManager.requestData(requestType: requestType, urlString: apiUrlString, params: body) { (response, error) in
            if error != nil
            {
                callBack(error, nil)
            }else{
                callBack(response, nil)
            }
            
        }
    }
    
}

extension LPBaseNetWorking{
    

   
}
